package Filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.logging.Filter;
import java.util.logging.LogRecord;

/**
 * Created by LENOVO on 2018/5/27.
 */
public class TimeFilter implements Filter {

    public static  class Timer{

        long time;

        public void start() {
            time = System.currentTimeMillis();
        }

        public void stop() {
            time = System.currentTimeMillis() - time;
        }

        public long getTime() {
            return time;
        }

        public Timer() {
            time=0L;
        }
    }

    public static final String s = "cjw.timer";
    private String key;

    public TimeFilter() {
        key = null;
    }



    public void init(FilterConfig filterConfig) throws ServletException {
        if(filterConfig.getInitParameter("key") != null) {
            key = filterConfig.getInitParameter("key");
        }else {
            key = s;
        }
    }


    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        Timer timer = new Timer();
        timer.start();
        request.setAttribute(key,timer);

        filterChain.doFilter(servletRequest,servletResponse);
        timer.stop();
        handleTimer(timer);
    }

    public void handleTimer(Timer timer1) {

    }


    public void destroy() {

    }


    @Override
    public boolean isLoggable(LogRecord record) {
        return false;
    }

}
